"""
@Project:ruiji
@File:index.py
@Author:马可
@Date:上午 09:38
"""
from email.mime import image
from itertools import count
import re
from flask import Blueprint,jsonify,request
from db import db
from utils.myredis import r
import json

index_blue = Blueprint('index',__name__)


# 获取商家信息
@index_blue.route("/getshops")
def getshops():
    code = '001'
    key = "shop"+code
    # r.removeall_str(key)   # 删除redis信息
    shop = r.get_str(key)
    if not shop:
        # 并发访问时允许一人访问
        res = r.setnx_str(key+'exit',key+'exit')
        # print('aaa')
        if res:
            print('bbb')
            sql = "select * from shops where code='001'"
            shop = db.find(sql)
            r.set_str(key,json.dumps(shop))
    else:
        shop = json.loads(shop)
    return jsonify({
        'code':200,
        'shops':shop,
    })


# 获取所有分类
@index_blue.route('/getcates')
def getcates():
    cates = r.get_str('cates')
    if not cates:
        sql = "select id,name from category order by sort asc"
        res = db.find_all(sql)
        r.set_str('cates',json.dumps(res))
    else:
        res = json.loads(cates)
    data = []
    if res:
        data = [{
            'id':str(i['id']),
            'text':i['name'],
        } for i in res]
    return jsonify({
        'code':200,
        'catelist':data,
    })



#根据分类id获取此分类下的所有商品
@index_blue.route("/getGoodsBycateid")
def getGoods():
    # 获取分类id
    cateid = request.args.get('cateid')
    # r.removeall_str('goods'+cateid)
    # 从缓存取数据
    goods = r.get_str('goods'+cateid)
    
    # 不存在查询
    if not goods:
        sql = "select id,name,price,image,description from dish where category_id=%d and is_deleted=0"%int(cateid)
        res = db.find_all(sql)
        # 吧decimal转成float
        data = []
        # 根据菜品id查询对应的口味信息
        for i in res:
            dict = {
                'id':str(i['id']),
                'name':i['name'],
                'price': float(i['price']),
                'image': i['image'],
                'description': i['description'],
                'flavors':[]
            }
            sql1 = "select value from dish_flavor where dish_id=%d"%int(i['id'])
            flavors = db.find_all(sql1)
            flist=[]
            for j in flavors:
                flist.append(json.loads(j['value']))
            dict['flavors'] = flist
            data.append(dict)
        # 加入缓存
        r.set_str('goods'+cateid,json.dumps(data))
    else:
        data = json.loads(goods)
    return jsonify({
        "code":200,
        "goods":data
    })



# 购物车添加
@index_blue.route('/addcate')
def addcart():
    # 获取参数
    userid = request.args.get('userid')
    gid = request.args.get('gid')
    count = request.args.get('count')
    type = request.args.get('type')
    flavors = request.args.get('flavors')
    # if not all [userid,gid,count,type,flavors]:
    #     return jsonify({'code':400,'msg':'参数错误'})
    # 查询购物车中某个商品是否存在
    pkey = 'cart' + str(userid) + 'goods' + str(gid)
    flag = r.is_exits(pkey)
    if int(flag)==0:
        # 不存在添加
        r.hash_add(pkey,gid,count)
        r.hash_add(pkey,'type',type)
        r.hash_add(pkey,'flavors',json.dumps(flavors))

    else:
        # 存在数量更新
        flavor1 = r.hash_items_value(pkey,'flavors').decode()
        if flavor1 != flavors:
            r.hash_add(pkey, gid, count)
            r.hash_add(pkey, 'type', type)
            r.hash_add(pkey, 'flavors', json.dumps(flavors))
        else:
            r.hash_hincrby(pkey,gid,count)
    # 返回结果
    return jsonify({
        "code":200,
        "msg":'购买成功'
    })


#我的购物车
@index_blue.route('/addcart')
def myshop():
    # 获取userid
    userid = request.args.get('userid')
    # 根据userid模糊查询购物车信息
    carts = r.findall_str('cart'+str(userid))
    # 遍历购物车，查每一个商品的属性
    clist = []
    for i in carts:
        dict={}
        goods = r.hash_getall(i.decode())
        for k,v in goods.items():
            kk = k.decode()
            vv = v.decode()
            if kk=="type":
                dict['type'] = vv
            elif kk=='flavors':
                dict['flavors'] =json.loads(vv)
            else:
                dict['id'] = kk
                dict['count'] = vv

        clist.append(dict)
    if len(clist)>0:
        # 根据商品id查询数据库价格
        for i in clist:
            # 根据id和类型查询名称和价格  1单品 2套餐
            if i['type'] == 1:
                sql = "select name,price from dish where id=%d"%int(i['id'])
            else:
                sql = "select name,price from dish where id=%d" % int(i['id'])
            res = db.find(sql)
            # 重组
            i['name'] = res['name']
            i['price'] = float(res['price'])
    # 返回结果 [{'id':'1',}]
    return jsonify({'code':200,'clist':clist})

def xtree(data):
    list1 = []
    # 判断data长度
    if len(data)<=0:
        return list1
    # 把data处理成字点
    dict = {}
    for i in data:
        dict[i['code']] = i

    for j in data:
        # 判断是否为一级
        pid = j['pid']
        if pid ==None:
            list1.append(j)
        else:
            # 判断这个id对应的父级有没有son
            if 'son' not in dict[pid]:
                dict[pid]['son']=[]
            dict[pid]['son'].append(j)
    return list1 


# 无限级分类、省市区
@index_blue.route('/index_blue')
def index_blues():
    # redis
    citylist = r.get_str("citylist")
    if not citylist:
        sql = "select * from tb_areas"
        res = db.find_all(sql)
        list = xtree(res)
        r.set_str('citylist',json.dumps(list))
    else:
        list = json.loads(citylist)
    return jsonify({
        "code":200,
        "list":list,
    })


@index_blue.route('/jiajian')
def jiajian():
    # 获取参数 userid  gid count type
    userid = request.args.get('userid')
    gid = request.args.get('gid')
    count = request.args.get('count')
    type = request.args.get('type')
    # 查询购物车中是否存在
    key = "cart"+str(userid)+'goods'+str(gid)
    if r.is_exits(key):
        tcount = count
        if type== 2:
            tcount = '-'+str(count)
        res = r.hash_hincrby(key,gid,tcount,type)
        # 判断结果
        if res == False:
            return jsonify({
                'code':10011,
                'msg':'件的数量必须小于购买数量'
            })
        else:
            return jsonify({
                'code':200,
                'msg':'成功',
            })
    else:
        return jsonify({
            'code':10010,
            'msg':'没买过该商品'
        })



